//
//  FancyDetailsController.swift
//  Fancyswap
//
//  Created by Francois Gratton on 2015-03-08.
//  Copyright (c) 2015 Jonathan Muschalle. All rights reserved.
//
// scroll_view.contentOffset

import UIKit

class FancyDetailsController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, UIScrollViewDelegate {
    
    @IBOutlet weak var orderBtn: UIButton!
    @IBOutlet weak var desc: UILabel!
    @IBOutlet weak var marqueNom: UILabel!
    @IBOutlet weak var prix: UILabel!
    @IBOutlet weak var taille: UILabel!
    @IBOutlet weak var colView: UICollectionView!
    @IBOutlet weak var pageCtrl: UIPageControl!

    var item: FancyItem?
    var selIndex: NSIndexPath?
    var lastSViewWidth: Int = 0
    var lastSViewHeight: Int = 0
    let fancyApi  = FancyRestApi()
    let loadingImg = UIImage(named: "blank.png")
    var ordered: Bool = false
    var dismissDelegate: protocol<FancyViewControllerProtocol>?

    override func viewDidLoad() {
        super.viewDidLoad()
        
        orderBtn.layer.cornerRadius = 10
        colView.delegate = self
        
        marqueNom.text = item!.brand
        prix.text = "\(item!.value) SwapCoins"
        taille.text = "Taille: \(item!.size)"
        desc.text = item!.name
        
        // use cached images or fetch details
        if self.item!.thumbs.count > 0
        {
            let count: Int = item!.imageCount()
            if count > 1 {
                self.pageCtrl.numberOfPages = count
            }
            else {
                self.pageCtrl.numberOfPages = 0
            }
            
            colView?.reloadData()
        }
        else
        {
            // fetch item's detail
            fancyApi.GetItemDetail(item!.id) {
                succeeded, msg, fiDetails in
                if succeeded
                {
                    self.item?.imageFiles = fiDetails!.imageFiles
                    for i in 0...self.item!.imageFiles.count-1
                    {
                        // when filename match, reuse thumbnail image
                        if self.item!.imageFiles[i].caseInsensitiveCompare(self.item!.image) == NSComparisonResult.OrderedSame && self.item!.thumbnail != nil
                        {
                            self.item!.thumbs.append(self.item!.thumbnail!)
                        }
                        else
                        {
                            self.item!.thumbs.append(self.loadingImg!)
                        }
                    }
                    let count: Int = self.item!.imageCount()
                    if count > 1 {
                        self.pageCtrl.numberOfPages = count
                    }
                    else {
                        self.pageCtrl.numberOfPages = 0
                    }
                    self.colView?.reloadData()
                }
                else
                {
                    let alert = UIAlertController(title: "", message: "Incapable de se connecter au serveur, SVP essayez plus tard.", preferredStyle: UIAlertControllerStyle.ActionSheet)
                    alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler:
                        {
                            action -> Void in
                            println("OK")
                        }
                        ))
                    
                    self.presentViewController(alert, animated: true) { () -> Void in }

                }
            }
        }
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell{
        var cell = collectionView.dequeueReusableCellWithReuseIdentifier("ImageCell", forIndexPath: indexPath) as FancyImageCell
        
        if item!.thumbs[indexPath.row] != loadingImg
        {
            cell.image.image = item!.thumbs[indexPath.row]
            cell.Loading.hidden = true
            cell.activitySpinner.stopAnimating()
            cell.lblError.hidden = true
        }
        else
        {
            cell.image.image = nil
            cell.Loading.hidden = false
            cell.activitySpinner.startAnimating()
            cell.activitySpinner.hidden=false
            cell.lblError.hidden = true
            
            let url = fancyApi.imageURL(item!.imageFiles[indexPath.row], size: ImageFormat.Thumbnail)
            
            fancyApi.GetDataFromUrl(url) {
                srcUrl, succeeded, msg, data in
                let filename = srcUrl.lastPathComponent
                let nsndx = self.IndexFromItemName(filename)
                if nsndx.row == -1 {
                    return
                }
                let _cell = self.colView?.cellForItemAtIndexPath(nsndx)
                if succeeded
                {
                    // set and cache fetched image
                    let img = UIImage(data: data!)
                    self.item!.thumbs[nsndx.row] = img!
                    
                    if _cell != nil
                    {
                        let loadingCell = _cell as FancyImageCell
                        
                        loadingCell.Loading.hidden = true
                        loadingCell.activitySpinner.stopAnimating()
                        loadingCell.image.image = img
                        loadingCell.lblError.hidden = true
                    }

                    self.colView.reloadItemsAtIndexPaths([nsndx])
                }
                else
                {
                    if _cell != nil
                    {
                        let loadingCell = _cell as FancyImageCell
                        loadingCell.Loading.hidden = true
                        loadingCell.activitySpinner.stopAnimating()
                        loadingCell.lblError.hidden = false
                    }
                }
            }
        }

        return cell
        
    }
    func getImageAtIndex(index:Int) -> UIImage
    {
        if index >= 0 && index < item!.thumbs.count
        {
            return item!.thumbs[index]
        }
        return UIImage()
    }
    func IndexFromItemName(filename: String) -> NSIndexPath {
        for i in 0...(item!.imageFiles.count-1)
        {
            if item!.imageFiles[i].caseInsensitiveCompare(filename) == NSComparisonResult.OrderedSame {
                return NSIndexPath(forRow: i, inSection: 0)
            }
        }
        return NSIndexPath(forRow: -1, inSection: 0)
    }

    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
        if item!.thumbs.count > 1
        {
            let img = getImageAtIndex(indexPath.row)
            
            let scaleWidth = colView.frame.size.width / img.size.width
            let scaleHeight = colView.frame.size.height / img.size.height
            let minScale = min(scaleHeight, scaleWidth)
            
            return CGSize(width:(img.size.width * minScale)-10
                , height: (img.size.height * minScale)-10)
        }
        
        return CGSize(width:self.colView.frame.size.width-10
            , height: self.colView.frame.size.height-10)
    }
    func updateCurrPage()
    {
        // pageCtrl hidden when only 1 image
        if item!.imageFiles.count == 1 {
            return
        }
        
        var visibleNdxs = colView.indexPathsForVisibleItems() as [NSIndexPath]
        
        if visibleNdxs.count < 1 {
            return
        }
        
        // sort visible items index descending
        visibleNdxs.sort({$0.row > $1.row})
        
        // from right most image to left
        for i in 0...(visibleNdxs.count-1)
        {
            let cel = colView.cellForItemAtIndexPath(visibleNdxs[i])! as UICollectionViewCell
            let cellFrameInSuperview = colView.convertRect(cel.frame, toView:colView.superview)
            // select as current page when more than half of image is visible
            if (colView.bounds.width - cellFrameInSuperview.origin.x) > (cellFrameInSuperview.width / 2) {
                pageCtrl.currentPage = visibleNdxs[i].row
                return
            }
        }
        // nothing found, select left most image as current page
        pageCtrl.currentPage = visibleNdxs[visibleNdxs.count-1].row
    }
    func scrollViewDidScroll(scrollView: UIScrollView) {
        updateCurrPage()
    }
    override func didRotateFromInterfaceOrientation(fromInterfaceOrientation: UIInterfaceOrientation) {
        colView.performBatchUpdates(nil, completion: nil)
        updateCurrPage()
    }
    override func viewDidAppear(animated: Bool) {

        if ordered {
            dismissDelegate?.dismissViewControllerAndTakeAction(self)
            return
        }
        colView.performBatchUpdates(nil, completion: nil)
        updateCurrPage()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        
        if segue.identifier == "showFullscreen" {
            let cell = sender as UICollectionViewCell
            let indexPath = colView?.indexPathForCell(cell)
            
            let fullscreenView = segue.destinationViewController as FullscreenController
            fullscreenView.lowResImage = self.item!.thumbs[indexPath!.row]
            fullscreenView.isBlankImg = fullscreenView.lowResImage == loadingImg
            fullscreenView.filename = self.item!.imageFiles[indexPath!.row]
        }
        else if segue.identifier == "ordering" {
            let orderView = segue.destinationViewController as OrderController
            orderView.item = self.item
            orderView.parentView = self
        }
    }
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{
        return item!.thumbs.count
    }
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return 1
    }

}
